package util

import (
	"github.com/dgrijalva/jwt-go"
	"time"
)

type Claims struct {
	AccountId string
	jwt.StandardClaims
}

var mySigningKey = []byte("wiki")

func GenerateToken(accountId string) (string, error) {
	nowTime := time.Now()
	expireTime := nowTime.Add(3000 * time.Second)
	issuer := "wiki"
	claims := Claims{
		AccountId: accountId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    issuer,
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(mySigningKey)
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})
	if err != nil {
		return nil, err
	}

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}
	return nil, err
}
